using System;
using System.Collections;
using UnityEngine;
public class WaitTimeTool
{
    private class WaitTimeMono : MonoBehaviour { }
    private static WaitTimeMono tool;

    static WaitTimeTool()
    {
        GameObject go = new GameObject("[WaitTimeTool]");
        GameObject.DontDestroyOnLoad(go);
        tool = go.AddComponent<WaitTimeMono>();
    }

    private static IEnumerator OpenCoroutine(float time, Action callback)
    {
        yield return new WaitForSeconds(time);
        if (callback != null) callback.Invoke();
    }

    private static IEnumerator OpenCoroutine<T>(float time, Action<T> callback, T value)
    {
        yield return new WaitForSeconds(time);
        if (callback != null) callback.Invoke(value);
    }


    /// <summary>等待 Time 开始执行 callback回调函数</summary>
    /// <param name="time">等待的时间</param>
    /// <param name="callback">回调函数</param>
    /// <returns></returns>
    public static Coroutine WaitTime(float time, Action callback)
    {
        return tool.StartCoroutine(OpenCoroutine(time, callback));
    }

    /// <summary>等待 Time 开始执行 callback回调函数</summary>
    /// <typeparam name="T">任意类型的一个参数</typeparam>
    /// <param name="time">等待的时间</param>
    /// <param name="callback">回调</param>
    /// <param name="value">参数值</param>
    /// <returns></returns>
    public static Coroutine WaitTime<T>(float time, Action<T> callback, T value)
    {
        return tool.StartCoroutine(OpenCoroutine(time, callback, value));
    }

    /// <summary>取消等待</summary>
    /// <param name="coroutine"></param>
    public static void CancelWait(ref Coroutine coroutine)
    {
        if (coroutine != null)
        {
            tool.StopCoroutine(coroutine);
            coroutine = null;
        }
    }

}